import React, { useState, Fragment } from 'react';
import { Table, Input, Button, Row, Col, Tooltip, Typography } from 'antd';
import { withRouter, router } from 'umi';
import Pagination from '@/components/Pagination';
import { useRequest, defaultFormatResult } from '@/hooks';
import { ENTRY_STATUS_MAP, sortStringToNumber } from '@/pages/EntryManage/utils';
import { toArray } from '@/utils/utils';
import moment from 'moment';
import useDictionary from '@/hooks/useDictionary';
import SelectPost from '@/pages/Recruitment/containers/select/SelectPost';
import authHelper from '@/utils/auth/helper';
import { eventTrack } from '@/utils/track';
import { get } from 'lodash';
import Icon from '@/components/IconPro';
import styles from './index.less';
import { queryCandidateProcessHistoryList, getOrganizationWithFullName } from '../services';

const { Paragraph } = Typography;
const { checkCode } = authHelper;

// 入职管理-历史记录
const EntryHistoryList = ({ location }) => {
    const { query = {} } = location;
    const { pageNo = 1, pageSize = 10 } = query;

    const [searchText, setSearchText] = useState(query?.entryPersonnelName);
    const [dutyCode, setDutyCode] = useState(query?.dutyCode);
    const [sexTypeList, getSexTypeText] = useDictionary('sexType');

    // 请求数据
    const { data, loading } = useRequest(
        () =>
            queryCandidateProcessHistoryList({
                pageNo,
                pageSize,
                ...query,
                order: sortStringToNumber(query?.order)
            }),
        {
            ready: !!query,
            refreshDeps: [query],
            ...defaultFormatResult
        }
    );
    const tableDataSource = data?.rows;
    const total = data?.total;

    // 获取面包屑机构路径
    const { run: runFullname, fetches: fullnameFetches } = useRequest(params => getOrganizationWithFullName(params), {
        manual: true,
        fetchKey: organizationCode => organizationCode,
        ...defaultFormatResult
    });

    // 替换url
    const handleReplacePage = param => {
        history.push({ query: { ...query, ...param } });
    };

    // 分页切换
    const handlePaginationChange = pagination => {
        handleReplacePage({ pageNo: pagination?.current, pageSize: pagination?.pageSize });
    };

    const columns = [
        {
            title: '姓名',
            dataIndex: 'employeeName',
            key: 'employeeName',
            width: 180,
            render: (text, record) => (
                <>
                    {checkCode('office:personnel:progress:entry:detail') ? (
                        <Button
                            type="link"
                            alt={text}
                            className={styles.link}
                            onClick={async () => {
                                await eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_entry_history_name_click',
                                    pageName: 'personnel_management_onboard_and_leave',
                                    eventProps: {
                                        click_context: text
                                    }
                                });
                                history.push({
                                    pathname:
                                        '/office/personnelManagement/onboardAndLeave/entryManage/entryEmployeeDetail',
                                    query: {
                                        entryPersonnelCode: record?.entryPersonnelCode
                                        // organizationCode: record?.organizationCode
                                    }
                                });
                            }}
                        >
                            {text}
                        </Button>
                    ) : (
                        text
                    )}
                </>
            )
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            width: 150,
            filteredValue: toArray(query?.sex),
            filterMultiple: false,
            filters: sexTypeList,
            render: text => getSexTypeText(text)
        },
        {
            title: '组织机构',
            dataIndex: 'organizationName',
            key: 'organizationName',
            render: (text, record) => {
                const { organizationCode } = record;
                return (
                    <Tooltip
                        title={
                            get(fullnameFetches[organizationCode], 'data[0].fullOrganizationName') || (
                                <Icon type="loading" />
                            )
                        }
                        onMouseEnter={() => {
                            if (!fullnameFetches[organizationCode]) {
                                runFullname([organizationCode]);
                            }
                        }}
                    >
                        <Paragraph ellipsis className={styles.listParagraph}>
                            {text}
                        </Paragraph>
                    </Tooltip>
                );
            }
        },
        {
            title: '岗位',
            dataIndex: 'dutyName',
            key: 'dutyName',
            render: (text, record) => (
                <>
                    <Row type="flex">
                        <Col>
                            <Tooltip title={text}>
                                <Paragraph ellipsis className={styles.listParagraph}>
                                    {text || '-'}
                                </Paragraph>
                            </Tooltip>
                        </Col>
                        <Col>{record?.rankValue ? `/${record.rankValue}` : '-'}</Col>
                    </Row>
                </>
            )
        },
        {
            title: '入职日期',
            dataIndex: 'entryDate',
            key: 'entryDate',
            sorter: true,
            sortOrder: query?.order,
            width: 150,
            render: text => moment(text).format('YYYY-MM-DD')
        },
        {
            title: '招聘负责人',
            dataIndex: 'recruitDirectorName',
            key: 'recruitDirectorName',
            render: text => text
        },
        {
            title: '状态',
            dataIndex: 'entryStatus',
            key: 'entryStatus',
            width: 150,
            render: text => ENTRY_STATUS_MAP[text]?.name
        }
    ];

    // 表格筛选、排序等操作
    const handleTableChange = (_, filters = {}, sorter) => {
        const { sex, organizationName } = filters;
        const { order } = sorter;

        handleReplacePage({
            sex: sex[0],
            organizationCodes: organizationName,
            order
        });
    };

    return (
        <Fragment>
            {/* 搜索 */}
            <div className={styles.searchWrap}>
                <Row type="flex" gutter={16}>
                    <Col>
                        <Input
                            placeholder="搜索姓名"
                            value={searchText}
                            onPressEnter={() => {
                                handleReplacePage({ pageNo: 1, entryPersonnelName: searchText, dutyCode });
                            }}
                            onChange={e => {
                                setSearchText(e.target.value);
                            }}
                            onFocus={() => {
                                eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_entry_history_name_input_click',
                                    pageName: 'personnel_management_onboard_and_leave'
                                });
                            }}
                            allowClear
                        />
                    </Col>
                    <Col>
                        <SelectPost
                            placeholder="岗位"
                            value={dutyCode}
                            onChange={setDutyCode}
                            onFocus={() => {
                                eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_entry_history_post_input_click',
                                    pageName: 'personnel_management_onboard_and_leave'
                                });
                            }}
                        />
                    </Col>
                    <Col>
                        <Button
                            type="primary"
                            onClick={() => {
                                eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_entry_history_search_submit_click',
                                    pageName: 'personnel_management_onboard_and_leave',
                                    eventProps: {
                                        click_context: `姓名：${searchText},岗位：${dutyCode}`
                                    }
                                });
                                handleReplacePage({ pageNo: 1, entryPersonnelName: searchText, dutyCode });
                            }}
                        >
                            搜索
                        </Button>
                    </Col>
                </Row>
            </div>
            <Table
                className={styles.entryListTable}
                loading={loading}
                rowKey="id"
                columns={columns}
                dataSource={tableDataSource}
                pagination={false}
                onChange={handleTableChange}
                scroll={{ x: 'max-content' }}
                rowClassName={record => (record?.entryStatus === 101 ? 'terminationStatus' : null)}
                style={{
                    tableLayout: 'fixed',
                    wordBreak: 'break-word'
                }}
            />
            {/* 分页 */}
            <Pagination
                current={query?.pageNo}
                pageSize={query?.pageSize}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />
        </Fragment>
    );
};

export default withRouter(EntryHistoryList);
